package fr.umlv.m2.recipes.ideas.features;

import android.database.sqlite.SQLiteDatabase;
import fr.umlv.m2.recipes.ideas.dao.IngredientDAO;
import fr.umlv.m2.recipes.ideas.dao.KeywordDAO;
import fr.umlv.m2.recipes.ideas.dao.RecipeDAO;
import fr.umlv.m2.recipes.ideas.dao.RecipeToIngredientDAO;
import fr.umlv.m2.recipes.ideas.dao.RecipeToKeywordDAO;
import fr.umlv.m2.recipes.ideas.dao.StepDAO;
import fr.umlv.m2.recipes.ideas.sqlite.db.objects.RecipesDB;

/**
 * Create a Singleton to create the database and to open a connection
 * @author Christophe Chillan
 *
 */
public class RecipeDatabaseUtilities {
	private static final RecipeDatabaseUtilities instance = new RecipeDatabaseUtilities();

	private RecipeDatabaseUtilities() {
	}

	/**
	 * Get an instance of {@link RecipeDatabaseUtilities}
	 * @return the singleton instance of the RecipeDatabaseUtilities
	 */
	public RecipeDatabaseUtilities getInstance() {
		return instance;
	}
	/**
	 * Create the database if it doesn't exist and insert lines in it
	 * @param features
	 */
	public static void createDatabase(RecipeGroupFeatures features) {
		if (RecipesDB.isOpen()) {
			SQLiteDatabase db = RecipesDB.getDatabase();
			// daos
			RecipeDAO recipeDAO = RecipesDB.getRecipeDao();
			IngredientDAO ingredientDAO = RecipesDB.getIngredientDao();
			RecipeToIngredientDAO recipeToIngredientDao = RecipesDB
					.getRecipesToIngredientDao();
			KeywordDAO keywordDAO = RecipesDB.getKeywordDao();
			RecipeToKeywordDAO recipeToKeywordDAO = RecipesDB
					.getRecipesToKeywordDao();
			StepDAO stepDao = RecipesDB.getStepDao();
			// insert
			/** RECIPE **/
			int start = recipeDAO.getLastInsertIdOfRecipe(db);
			int i=0;
			for (i=start;i<features.getRecipes().size();i++) {
				recipeDAO.insert(db, features.getRecipes().get(i));
			}

			/** INGREDIENT **/
			start = ingredientDAO.getLastInsertIdOfIngredient(db);
		
			for(i=start;i<features.getIngredients().size();i++){
				ingredientDAO.insert(db, features.getIngredients().get(i));
			}
			

			/** RECIPE TO INGREDIENT **/
			start=recipeToIngredientDao.getCountInstances(db);
			for (i=start;i<features.getRecipesToIngredients().size();i++) {
				recipeToIngredientDao.insert(db, features.getRecipesToIngredients().get(i));
			}

			/** KEYWORD **/
			start=keywordDAO.getLastInsertIdOfKeyword(db);		
			for(i=start;i<features.getKeywords().size();i++){
				keywordDAO.insert(db, features.getKeywords().get(i));
			}			

			/** RECIPE TO KEYWORD **/
			start = recipeToKeywordDAO.getCountInstances(db);
			for (i=start;i<features.getRecipesToKeywords().size();i++) {
				recipeToKeywordDAO.insert(db, features.getRecipesToKeywords().get(i));
			}

			/** STEP **/
			start = stepDao.getLastInsertIdOfStep(db);
			for (i=start;i<features.getSteps().size();i++) {
				stepDao.insert(db, features.getSteps().get(i));
			}
		}

	}

}
